package club.vann.nowcoder;

import java.util.ArrayList;

/**
 * <p>难度：Medium</p>
 * <p>题目：螺旋矩阵</p>
 * <p>描述：给定一个m x n大小的矩阵（m行，n列），按螺旋的顺序返回矩阵中的所有元素。
 * 示例1
 * 输入
 * 复制
 * [[1,2,3],[4,5,6],[7,8,9]]
 * 返回值
 * 复制
 * [1,2,3,6,9,8,7,4,5]</p>
 * @author vann
 * @program now-coder
 * @description
 * @date 2021-03-23:16:43:56
 */
public class NC38 {
    public static void main(String[] args) {
        NC38 nc38 = new NC38();

        ArrayList<Integer> ans = null;
        ans = nc38.spiralOrder(TestCase.MATRIX);
        ans = nc38.spiralOrder(TestCase.MATRIX1);
        System.out.println("Success");
    }

    /**
     * 解法一：
     *
     * @param matrix
     * @return
     */
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> ans = new ArrayList<>();
        if(matrix == null || matrix.length == 0) {
            return ans;
        }
        int m = matrix.length;
        int n = matrix[0].length;

        int left = 0, right = n-1;
        int top = 0, bottom = m-1;
        int x = 0, y = 0;
        int count = 0;
        while(count < m*n) {
            for(int i = left; i <= right && count < m*n; i ++) {
                ans.add(matrix[top][i]);
                count ++;
            }
            top ++;

            for(int i = top; i <= bottom && count < m*n; i ++) {
                ans.add(matrix[i][right]);
                count ++;
            }
            right --;

            for(int i = right; i >= left && count < m*n; i --) {
                ans.add(matrix[bottom][i]);
                count ++;
            }
            bottom --;

            for(int i = bottom; i >= top && count < m*n; i --) {
                ans.add(matrix[i][left]);
                count ++;
            }
            left ++;
        }
        return ans;
    }

    static class TestCase {
        public static int[][] MATRIX = {{1,2,3},{4,5,6},{7,8,9}};
        public static int[][] MATRIX1 = {{1,2,3}};
    }
}
